console.log("脚本加载完毕")
gameInfo = {
    roomId: null,
    thisUserId: null,
    thatUserId: null,
    isWhite: true,
}

//////////////////////////////////////////////////
// 设定界⾯显⽰相关操作
//////////////////////////////////////////////////
function setScreenText(me) {
    let screen = document.querySelector('#screen');
    if (me) {
    screen.innerHTML = "轮到你落⼦了!";
    } else {
    screen.innerHTML = "轮到对⽅落⼦了!";
    }
}
   //////////////////////////////////////////////////
   // 初始化 websocket
   //////////////////////////////////////////////////
    let websocketURL = "ws://"+location.host+"/game";
    let websocket = new WebSocket(websocketURL);
   
   websocket.onclose = function(){
    console.log("连接建立");
    }
    websocket.onclose = function(){
        console.log("连接关闭")
    }
    websocket.onerror = function(){
        console.log("连接异常")
    }
    websocket.onmessage = function(event){
        console.log("[handlerGameReady]"+event.data);
        // 将数据转换为JS格式
        let resp = JSON.parse(event.data);
        if(!resp.ok){
            console.log("连接建立失败，请返回重连！");
            location.href = "/gobang_gamehall.html";
            return;
        }
        if(resp.message == "gameReady"){
            // 返回数据正确
            gameInfo.roomId = resp.roomId;
            gameInfo.thisUserId = resp.thisUserId;
            gameInfo.thatUserId = resp.thatUserId;
            //这里要判定先手方和当前用户相不相等
            gameInfo.isWhite = (resp.whiteUser == resp.thisUserId);

            //初始化棋盘
            initGame();

            //设置棋盘区域显示的内容
            setScreenText(gameInfo.isWhite);
        //     检测到多开
        } else if(resp.message == "repeatConnection"){
            alert("当前账号已在其他设备登陆！")
            location.href = "/gobang_login.html"
        }



    }
      
   //////////////////////////////////////////////////

   // 初始化⼀局游戏
//////////////////////////////////////////////////
function initGame() {
    // 是我下还是对⽅下. 根据服务器分配的先后⼿情况决定
    let me = gameInfo.isWhite;
    // 游戏是否结束
    let over = false;
    let chessBoard = [];
    //初始化chessBord数组(表⽰棋盘的数组)
    for (let i = 0; i < 15; i++) {
        chessBoard[i] = [];
        for (let j = 0; j < 15; j++) {
            chessBoard[i][j] = 0;
        }
    }
    let chess = document.querySelector('#chess');
    let context = chess.getContext('2d');
    context.strokeStyle = "#BFBFBF";
    // 背景图⽚
    let logo = new Image();
    logo.src = "img/div.png";
    logo.onload = function () {
        context.drawImage(logo, 0, 0, 450, 450);
        initChessBoard();
    }
    // 绘制棋盘⽹格
    function initChessBoard() {
        for (let i = 0; i < 15; i++) {
            context.moveTo(15 + i * 30, 15);
            context.lineTo(15 + i * 30, 430);
            context.stroke();
            context.moveTo(15, 15 + i * 30);
            context.lineTo(435, 15 + i * 30);
            context.stroke();
        }
    }
    // 绘制⼀个棋⼦, me 为 true
    function oneStep(i, j, isWhite) {
        context.beginPath();
        context.arc(15 + i * 30, 15 + j * 30, 13, 0, 2 * Math.PI);
        context.closePath();
        var gradient = context.createRadialGradient(15 + i * 30 + 2, 15 + j * 
            30 - 2, 13, 15 + i * 30 + 2, 15 + j * 30 - 2, 0);
        if (!isWhite) {
            gradient.addColorStop(0, "#0A0A0A");
            gradient.addColorStop(1, "#636766");
        } else {
            gradient.addColorStop(0, "#D1D1D1");
            gradient.addColorStop(1, "#F9F9F9");
        }
            context.fillStyle = gradient;
            context.fill();
    }

    chess.onclick = function (e) {

        if (over) {
            return;
        }
        if (!me) {
            return;
        }
        let x = e.offsetX;
        let y = e.offsetY;
        // 注意, 横坐标是列, 纵坐标是⾏
        let col = Math.floor(x / 30);
        let row = Math.floor(y / 30);
        console.log(chessBoard[row][col]);
        if (chessBoard[row][col] == 0) {
            // 在点击棋盘后先不绘制棋子，先向服务器发送请求，等到服务器返回响应时，再进行绘制
            //  发送坐标给服务器, 服务器要返回结果
            send(row, col)


        }
    }
 //  实现发送落⼦请求逻辑, 和处理落⼦响应逻辑.
    function send(row, col){
        let req = {
            message: "putChess",
            userId: gameInfo.thisUserId,
            row: row,
            col: col,
        }
        console.log(JSON.stringify(req));
        websocket.send(JSON.stringify(req));
    }

    //原本的onmessage是用来处理连接就绪响应，这里重写onmessage, 用来处理落子响应
    websocket.onmessage = function (event){
        console.log("[HandlerPutChess]" + event.data);
        //将服务器发来的数据进行处理
        let responds = JSON.parse(event.data);
        if(responds.message !== "putChess"){
            console.log("错误的响应结果");
        }
        if(responds.userId === gameInfo.thisUserId){
            oneStep(responds.col, responds.row, gameInfo.isWhite);
        } else if(responds.userId === gameInfo.thatUserId){
            //若不是该玩家发起的落子请求就绘制与该玩家相反的棋子色
            oneStep(responds.col, responds.row, !gameInfo.isWhite);
        }else {
            console.log("绘制棋子响应返回的id值有误");
            return;
        }
        chessBoard[responds.row][responds.col] = 1;

        //交换落子轮次
        me = !me;
        setScreenText(me);

        //判断游戏是否结束
        if(responds.winner !== 0){
            let screenDiv = document.querySelector("#screen");
            if(responds.winner === gameInfo.thisUserId){
                // alert("你赢了！")
                screenDiv.innerHTML = "YOU WIN";
            }else if(responds.winner === gameInfo.thatUserId){
                // alert("你输了！")
                screenDiv.innerHTML = "YOU LOSE";
            }else {
                alert("winner字段错误" + winner);
            }
            //游戏结束，回到游戏大厅
            // location.href = "/gobang_gamehall.html"

            // 添加按钮，用户点击后再跳转回大厅页面
            let backBTN = document.createElement("button");
            backBTN.innerHTML = "GO BACK";
            backBTN.onclick = function (){
                location.replace("/gobang_gameroom.html");;
            }
            let fatherDiv = document.querySelector(".container>div");
            fatherDiv.appendChild(backBTN);
        }
    }

}
